#include "Persecutor.h"

#include "ParticleBase.h"
#include "DescriptorParticle.h"
#include "ParticleContext.h"
#include "ParticleObserver.h"
#include "FileAccess.h"

#include "Engine.h"

using namespace ParticleEngine;

#define MOVE_SPEED 0.02f
#define ZOOM_MIN 0.002f
#define ZOOM_MAX 0.150f

Persecutor::Persecutor(ParticleContext& NewContext) :
Pos(Vec<2, float>((float)NewContext.Space_SizeX / 2.f, (float)NewContext.Space_SizeY / 2.f)),
Zoom(Zoom = ZOOM_MIN * 4.f),//geht irgendwie nicht
FocusParticle(nullptr),
Context(NewContext)
{
}

Persecutor::~Persecutor(void)
{
}

void Persecutor::Refresh()
{
	if (FocusParticle)
	{
		Pos = FocusParticle->Pos;
	}
}

void Persecutor::Move(Vec<2, float> PosChange, float ZoomChange)
{
	const Vec<2, float> FloatSpaceSize((float)Context.Space_SizeX, (float)Context.Space_SizeY);

	Pos += (PosChange / Zoom) * MOVE_SPEED;
	if (Pos.Y > FloatSpaceSize.Y) Pos.Y = FloatSpaceSize.Y;
	if (Pos.Y < 0.f) Pos.Y = 0.f;
	if (Pos.X >FloatSpaceSize.X) Pos.X = FloatSpaceSize.X;
	if (Pos.X < 0.f) Pos.X = 0.f;

	Zoom *= 1.f + ZoomChange * MOVE_SPEED;
	if (Zoom < ZOOM_MIN) Zoom = ZOOM_MIN;
	if (Zoom > ZOOM_MAX) Zoom = ZOOM_MAX;
}

void Persecutor::BindParticle()
{
	if (FocusParticle)
	{
		Audio.Stop();
		dynamic_cast<ParticleObserver*>(FocusParticle)->IsFocused = false;
		FocusParticle = nullptr;
		return;
	}

	Audio.Stop();
	/*
	for (size_t i = 0; i < Context.ParticleCount; i++)
	{
		if (Context.Par[i]->Descriptor->Name == std::string("Observer"))
		{
			FocusParticle = Context.Par[i];
			dynamic_cast<ParticleObserver*>(FocusParticle)->IsFocused = true;
			if (Context.Eng.GetIdleStatus() == false)
				Audio.Play();
			return;
		}
	}*/

	FocusParticle = nullptr;
}


void Persecutor::Unbind()
{
	Audio.Stop();
	FocusParticle = nullptr;
}


void Persecutor::Save(std::ofstream& Stream)
{
	size_t FileValue = 0;
	if (FocusParticle != nullptr)
		FileValue = FocusParticle->Index;

	FileAccess::WriteByRef(Stream, FileValue);
}

void Persecutor::Load(std::ifstream& Stream)
{
	Audio.Stop();

	const size_t FileValue = FileAccess::Read_size_t(Stream);
	/*
	if (FileValue > 0)
	{
		FocusParticle = Context.Par[FileValue];
		dynamic_cast<ParticleObserver*>(FocusParticle)->IsFocused = true;
	}
	else
	{
		FocusParticle = nullptr;
	}*/
}



void Persecutor::SetIdleStatusTrue()
{
	if (FocusParticle)
	{
		Audio.Stop();
	}
};


void Persecutor::SetIdleStatusFalse()
{
	if (FocusParticle)
	{
		Audio.Play();
	}
};